<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>角色管理</title>
    <!-- 字体图标样式 -->
    <link rel="stylesheet" href="../../css/iconfont.css">
    <!-- 引入bootstrap全局样式 -->
    <link rel="stylesheet" href="../../lib/bootstrap/css/bootstrap.min.css">
    <!-- 引入layui核心样式 -->
    <link rel="stylesheet" href="../../lib/layui/css/layui.css"/>
    <!-- 分页区域的样式 -->
    <link rel="stylesheet" href="../../css/footer.css">
    <!-- 先引入jQuery -->
    <script src="../../lib/jQuery/jquery-3.7.1.min.js"></script>
    <script src="../../lib/bootstrap/js/bootstrap.min.js"></script>
    <style>
        th, td {
            vertical-align: middle !important;
            text-align: center;
        }
        button {
            outline: none !important;
            border: none !important;
        }
        .form-inline>div.form-group {
            vertical-align: baseline;
        }
        .form-inline>div.form-group:not(:last-child) {
            margin-right: 20px;
        }
        .form-inline>div.form-group:last-child {
            float: right;
        }
        .form-inline>div.form-group>.icon-shuaxin {
            cursor: pointer;
            margin-left: 20px;
        }

        .message {
            display: none;
            width: auto;
            position: fixed;
            top: 20%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    </style>
    <script>
        // 全局的当前页码
        let currentPage
        // 全局的总页数
        let totalPage
        // 全局的表格行数
        let count
        // 发送请求的type类型
        let addOrEdit

        $(document).ready(function () {
            currentPage = 1
            queryPage()
        })

        /**
         * 把页面上所有关于分页和条件的参数打包发送请求，获取分页数据
         */
        function queryPage() {
            count = 0
            $.ajax({
                // http://localhost:8080/soms/server/role
                // 现在所在的目录：http://localhost:8080/soms/page/role/
                // http://localhost:8080/soms/page/role/server/role
                // url: '../../server/role', // 相当路径写法
                url: '/soms/server/role', // 绝对路径写法
                type: 'POST',
                data: {
                    type: 'queryPage',
                    currentPage: currentPage,
                    pageSize: $('#pageSize').val(),
                    roleCode: $("#roleCode").val(),
                    roleName: $("#roleName").val(),
                    createdBegin: $("#createdBegin").val(),
                    createdEnd: $("#createdEnd").val()
                },
                success: function (result) {
                    if (result.code === 200) {
                        // 渲染页面
                        renderPage(result.data) // pageInfo
                    } else if (result.code === 401) {
                        // 跳转回登录页
                        parent.location.href = '../../no_auth.html'
                    } else {
                        // 提示
                        alertMessage(result.msg, false, 2000)
                    }
                },
                error: function (error) {
                    // 提示
                    alertMessage('请求失败', false, 2000)
                }
            })
        }

        /**
         * 分页数据
         * @param page 后端的pageInfo
         */
        function renderPage(page) {
            // 渲染表格
            let dataList = page.data
            let tbody_html = ''
            if (dataList.length > 0) {
                count = dataList.length
                for (let i = 0; i < dataList.length; i++) {
                    let row = dataList[i]
                    tbody_html += '<tr>'
                    tbody_html += '<td>' + row.roleCode + '</td>'
                    tbody_html += '<td>' + row.roleName + '</td>'
                    tbody_html += '<td>' + row.creatorName + '</td>'
                    tbody_html += '<td>' + row.created + '</td>'
                    tbody_html += '<td>' + row.modifierName + '</td>'
                    tbody_html += '<td>' + row.modified + '</td>'
                    tbody_html += '<td>'
                    tbody_html += "<button type='button' class='btn btn-info btn-xs' onClick='openModalForEdit("
                    tbody_html += row.id
                    tbody_html += ")' data-toggle='modal' data-target='#roleModal'>编辑</button>"
                    tbody_html += '\n'
                    tbody_html += "<button type='button' class='btn btn-danger btn-xs' onclick='openModalForDelete("
                    tbody_html += row.id
                    tbody_html += ")' data-toggle='modal' data-target='#deleteModal'>删除</button>"
                    tbody_html += '</td>'
                    tbody_html += '</tr>'
                }
            }
            $('#table-data').html(tbody_html)
            // 渲染当前页
            currentPage = page.currentPage
            $('#current-page').text(currentPage)
            // 渲染总页数
            totalPage = page.totalPage
            $('#total-page').text(totalPage)
            // 渲染总条数
            $('#total-count').text(page.totalCount)
            // 导航页码的输入框清空
            $('#toIndex').val('')
        }

        /**
         * 刷新角色管理
         */
        function reloadPage() {
            // 查询表单清空
            $('.layui-card-header>.form-inline')[0].reset()
            // 页码回到1
            currentPage = 1
            queryPage()
        }

        /**
         * 条件查询
         */
        function queryByParams() {
            currentPage = 1
            queryPage()
        }

        /**
         * 切换到目标页
         *
         * @param index
         */
        function toPageIndex(index) {
            // 超出页码范围，或者页码不变化，终止翻页
            if (index < 1 || index > totalPage || index === currentPage) {
                return
            }
            currentPage = index
            queryPage()
        }

        /**
         * 每页数量改变，重新查询
         */
        function changePageSize() {
            currentPage = 1
            queryPage()
        }

        /**
         * 打开新增角色的模态框
         */
        function openModalForAdd() {
            // 修改模态框标题
            $('#roleModalLabel').text("新增角色")
            // 清空模态框表单的字段，一定需要dom对象来执行reset()方法
            // document.getElementById('dialog-form').reset()
            $('#dialog-form')[0].reset()
            $('#role_id').val('')
            addOrEdit = 'add'
        }

        /**
         * 打开编辑角色的模态框
         * @param id 被修改数据的表id
         */
        function openModalForEdit(id) {
            // 修改模态框标题
            $('#roleModalLabel').text("编辑角色")
            // 清空模态框表单的字段，一定需要dom对象来执行reset()方法
            // document.getElementById('dialog-form').reset()
            $('#dialog-form')[0].reset()
            $('#role_id').val(id)
            addOrEdit = 'edit'
            $.ajax({
                url: '/soms/server/role?type=queryById&id=' + id,
                type: 'GET',
                success: function (result) {
                    if (result.code === 200) {
                        $('#role_code').val(result.data.roleCode)
                        $('#role_name').val(result.data.roleName)
                    } else {
                        alertMessage(result.msg, false, 2000)
                        // 不打开模态框
                        $('#roleModal').modal('hide')
                        // 刷新页面
                        if (count === 1 && currentPage > 1) {
                            toPageIndex(currentPage - 1)
                        } else {
                            queryPage()
                        }
                    }
                },
                error: function (error) {
                    alertMessage('请求失败', false, 2000)
                }
            })
        }

        /**
         * 发送新增或编辑请求
         */
        function toAddOrEdit() {
            $.ajax({
                url: '/soms/server/role',
                type: 'POST',
                data: {
                    type: addOrEdit,
                    id: $('#role_id').val(),
                    roleCode: $('#role_code').val(),
                    roleName: $('#role_name').val()
                },
                success: function (result) {
                    if (result.code === 200) {
                        // 关闭模态框
                        $('#roleModal').modal('hide')
                        alertMessage('操作成功', true, 2000)
                        // 刷新角色管理
                        queryPage()
                    } else {
                        alertMessage(result.msg, false, 2000)
                    }
                },
                error: function (error) {
                    alertMessage('请求失败', false, 2000)
                }
            })
        }

        /**
         * 打开删除角色的提示框
         * @param id
         */
        function openModalForDelete(id) {
            $('#delete_id').val(id)
        }

        /**
         * 发起删除请求
         */
        function toDelete() {
            $.ajax({
                url: '/soms/server/role',
                type: 'POST',
                data: {
                    type: 'deleteById',
                    id: $('#delete_id').val()
                },
                success: function (result) {
                    if (result.code === 200) {
                        // 关闭模态框
                        $('#deleteModal').modal('hide')
                        alertMessage('操作成功', true, 2000)
                        // 刷新角色管理
                        // 可能出现当前页已经没数据的情况，根据删除之前的表格数据量是否为1来判断
                        if (count === 1 && currentPage > 1) {
                            toPageIndex(currentPage - 1)
                        } else {
                            queryPage()
                        }
                    } else {
                        if (result.msg === '数据已不存在') {
                            $('#deleteModal').modal('hide')
                            if (count === 1 && currentPage > 1) {
                                toPageIndex(currentPage - 1)
                            } else {
                                queryPage()
                            }
                        }
                        alertMessage(result.msg, false, 2000)
                    }
                },
                error: function (error) {
                    alertMessage('请求失败', false, 2000)
                }
            })
        }

        /**
         * 弹出消息提示
         * @param msg 消息内容
         * @param isSuccess 是否正常
         * @param timeout 保留的时间
         */
        function alertMessage(msg, isSuccess, timeout) {
            $('.message')
                .text(msg)
                .removeClass('alert-success')
                .removeClass('alert-danger')
                .addClass(isSuccess === true ? 'alert-success' : 'alert-danger')
                .css('z-index', '10000')
                .fadeIn()
            setTimeout(function () {
                $('.message').fadeOut()
            }, timeout)
        }
    </script>
</head>
<body>
<div class="layui-card layui-panel" style="margin: 15px">
    <div class="layui-card-header">
        <form class="form-inline">
            <div class="form-group">
                <label for="roleCode">角色编码</label>
                <input type="text" class="form-control" id="roleCode" placeholder="SOMS_ADMIN">
            </div>
            <div class="form-group">
                <label for="roleName">角色名称</label>
                <input type="text" class="form-control" id="roleName" placeholder="系统管理员">
            </div>
            <div class="form-group">
                <label>
                    创建时间
                    <input type="datetime-local" class="form-control" id="createdBegin">
                    <input type="datetime-local" class="form-control" id="createdEnd">
                </label>
            </div>
            <div class="form-group">
                <button type="button" class="btn btn-success" onclick="queryByParams()">查询</button>
            </div>
            <div class="form-group">
                <button type="button" class="btn btn-primary" onclick="openModalForAdd()"
                        data-toggle="modal" data-target="#roleModal">新增</button>
                <i class="iconfont icon-shuaxin" onclick="reloadPage()"></i>
            </div>
        </form>
    </div>
    <div class="layui-card-body">
        <!-- 数据表格 -->
        <table class="table table-striped table-bordered table-hover">
            <thead>
                <tr>
                    <th style="width: 15%">角色编码</th>
                    <th style="width: 15%">角色名称</th>
                    <th style="width: 15%">创建者</th>
                    <th style="width: 15%">创建时间</th>
                    <th style="width: 15%">修改者</th>
                    <th style="width: 15%">修改时间</th>
                    <th style="width: 10%">操作</th>
                </tr>
            </thead>
            <tbody id="table-data">
                <tr>
                    <td>SOMS_ADMIN</td>
                    <td>系统管理员</td>
                    <td>系统管理员</td>
                    <td>2016-04-13 00:00:00</td>
                    <td></td>
                    <td></td>
                    <td>
                        <button type="button" class="btn btn-info btn-xs" onclick="openModalForEdit(1)"
                                data-toggle="modal" data-target="#roleModal">编辑</button>
                        <button type="button" class="btn btn-danger btn-xs" onclick="openModalForDelete(1)"
                                data-toggle="modal" data-target="#deleteModal">删除</button>
                    </td>
                </tr>
                <tr>
                    <td>SOMS_ADMIN</td>
                    <td>系统管理员</td>
                    <td>系统管理员</td>
                    <td>2016-04-13 00:00:00</td>
                    <td></td>
                    <td></td>
                    <td>
                        <button type="button" class="btn btn-info btn-xs" onclick="openModalForEdit(2)"
                                data-toggle="modal" data-target="#roleModal">编辑</button>
                        <button type="button" class="btn btn-danger btn-xs" onclick="openModalForDelete(2)"
                                data-toggle="modal" data-target="#deleteModal">删除</button>
                    </td>
                </tr>
                <tr>
                    <td>SOMS_ADMIN</td>
                    <td>系统管理员</td>
                    <td>系统管理员</td>
                    <td>2016-04-13 00:00:00</td>
                    <td></td>
                    <td></td>
                    <td>
                        <button type="button" class="btn btn-info btn-xs" onclick="openModalForEdit(3)"
                                data-toggle="modal" data-target="#roleModal">编辑</button>
                        <button type="button" class="btn btn-danger btn-xs" onclick="openModalForDelete(3)"
                                data-toggle="modal" data-target="#deleteModal">删除</button>
                    </td>
                </tr>
                <tr>
                    <td>SOMS_ADMIN</td>
                    <td>系统管理员</td>
                    <td>系统管理员</td>
                    <td>2016-04-13 00:00:00</td>
                    <td></td>
                    <td></td>
                    <td>
                        <button type="button" class="btn btn-info btn-xs" onclick="openModalForEdit(4)"
                                data-toggle="modal" data-target="#roleModal">编辑</button>
                        <button type="button" class="btn btn-danger btn-xs" onclick="openModalForDelete(4)"
                                data-toggle="modal" data-target="#deleteModal">删除</button>
                    </td>
                </tr>
            </tbody>
        </table>
        <!-- 分页操作 -->
        <footer>
            <div>
                <p>共有<span id="total-count">0</span>条数据记录</p>
                <p><span id="current-page">1</span>/<span id="total-page">1</span>页</p>
            </div>
            <ul>
                <!-- 全局记录了一个currentPage -->
                <!-- 要阻止a标签自带的点击事件：href="javascript:;" -->
                <li><a href="javascript:;" onclick="toPageIndex(1)">首页</a></li>
                <li><a href="javascript:;" onclick="toPageIndex(currentPage - 1)">上一页</a></li>
                <li><a href="javascript:;" onclick="toPageIndex(currentPage + 1)">下一页</a></li>
                <li><a href="javascript:;" onclick="toPageIndex(totalPage)">最后一页</a></li>
            </ul>
            <div style="margin-left: 20px">
                <select id="pageSize" class="form-control" onchange="changePageSize()">
                    <option value="5">5条/页</option>
                    <option selected value="10">10条/页</option>
                    <option value="20">20条/页</option>
                </select>
            </div>
            <div style="margin-left: 20px">
                <span style="white-space: nowrap">跳转到</span>
                <input id="toIndex" class="form-control" type="number" style="width: 60px; margin: 0 3px"/>页
                <button class="btn btn-default" onclick="toPageIndex(+$('#toIndex').val())">GO</button>
            </div>
        </footer>
    </div>
</div>

<!-- 新增/编辑的模态框 -->
<div class="modal fade" id="roleModal" tabindex="-1" role="dialog" aria-labelledby="roleModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="roleModalLabel">
                    新增角色
                </h4>
            </div>
            <div class="modal-body">
                <!-- 要处理的是新增和编辑 -->
                <form id="dialog-form">
                    <input type="hidden" class="form-control" id="role_id">
                    <div class="form-group">
                        <label for="role_code">角色编码</label>
                        <input type="text" class="form-control"
                               id="role_code" placeholder="SOMS_ADMIN">
                    </div>
                    <div class="form-group">
                        <label for="role_name">角色名称</label>
                        <input type="text" class="form-control"
                               id="role_name" placeholder="系统管理员">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="toAddOrEdit()">提交</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认的模态框 -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="deleteModalLabel">
                    删除确认
                </h4>
            </div>
            <div class="modal-body">
                <input type="hidden" class="form-control" id="delete_id">
                您正在删除重要数据，确定删除吗？删除之前请确保该角色不被用户使用！
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="toDelete()">删除</button>
            </div>
        </div>
    </div>
</div>

<!-- 消息提示 -->
<div class="alert alert-success message" role="alert"></div>
</body>
</html>